package usersManagement.security;

import org.apache.shiro.authc.credential.*;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.web.env.DefaultWebEnvironment;
import org.apache.shiro.web.env.EnvironmentLoaderListener;
import org.apache.shiro.web.env.WebEnvironment;
import org.slf4j.Logger;
import usersManagement.util.AppLog;

import javax.inject.Inject;
import javax.servlet.ServletContext;

/**
 * User: eluibon
 * Date: 11/12/12
 * Time: 19.29
 * CDI Listener to inject a JPA Realm into Shiro for authetication via JPA instead of JDBC
 * currently not enabled
 */
public class CdiEnvironmentLoaderListener extends EnvironmentLoaderListener {

    @Inject @AppLog Logger log ;

    @Inject JpaRealm jpaRealm;

    @Override
    protected WebEnvironment createEnvironment(ServletContext sc) {

        WebEnvironment environment = super.createEnvironment(sc);

        RealmSecurityManager rsm = (RealmSecurityManager) environment.getSecurityManager();

        SimpleCredentialsMatcher simpleCredentialsMatcher = new SimpleCredentialsMatcher() ;
        jpaRealm.setCredentialsMatcher(simpleCredentialsMatcher);

        rsm.setRealm(jpaRealm);

        ((DefaultWebEnvironment) environment).setSecurityManager(rsm);

        return environment;
    }
}
